package dale.web.core.interceptor;

import javax.servlet.http.*;

import org.slf4j.*;
import org.springframework.web.servlet.*;

import dale.web.core.util.AuthHttpUtils;

public class AuthInterceptor implements HandlerInterceptor {

	private static final Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);
	
	public AuthInterceptor() {
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (AuthHttpUtils.permits(request)) {
			logger.debug("The request is permitted.");
			return true;
		} else {
			logger.debug("The reqeust is blocked.");
			String origin = getOrgin(request);
			response.sendRedirect(request.getContextPath() + "/user/signIn?origin=" + origin);
			/*RequestDispatcher dispatcher = request.getRequestDispatcher("/user/userLogIn");
			dispatcher.forward(request, response);*/
			return false;
		}
	}

	private String getOrgin(HttpServletRequest request) {
		String servletPath = request.getServletPath() == null ? "" : request.getServletPath();
		String queryString = request.getQueryString() == null ? "" : "?" +request.getQueryString();
		return servletPath + queryString;
	}

	public void postHandle(HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, Object obj, ModelAndView modelandview) throws Exception {
	}

	public void afterCompletion(HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, Object obj, Exception exception) throws Exception {
	}

}
